package com.thghh;

import com.thghh.table.ElegantTableModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 基于对象格式的TableModel
 *
 * @author Administrator
 *
 */
public class UserTableModelDemo {

    public static void main(String[] args) {

        final int WIDTH = 700;
        final int HEIGHT = 500;
        final int USER_SIZE = 10;

        final JFrame frame = new JFrame();
        frame.setTitle("基于面向对象的TableModel测试");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JTable table = new JTable();
        table.setFillsViewportHeight(true);
        table.setRowHeight(30);
        List<User> users = new ArrayList<User>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId(i);
            u.setUsername("username" + i);
            u.setPassword("123");
            u.setAge(i + 20);
            u.setIsMarry(i % 2 == 0);
            users.add(u);
        }

        final ElegantTableModel<User> tableModel = new ElegantTableModel(User.class, users);
        table.setModel(tableModel);

        frame.add(new JScrollPane(table));

        Panel panel = new Panel();

        JButton addBtn = new JButton("添加用户");
        JButton deleteBtn = new JButton("删除用户（按照行来删除）");
        JButton deleteBtn2 = new JButton("删除用户（按照对象来删除）");
        JButton updateBtn = new JButton("更新用户");

        panel.add(addBtn);
        panel.add(deleteBtn);
        panel.add(deleteBtn2);
        panel.add(updateBtn);

        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(frame, true);
                dialog.setSize(300, 300);

                JLabel idLab = new JLabel("用户编号:");
                final JTextField idTextField = new JTextField(25);

                JLabel nameLab = new JLabel("用户姓名");
                final JTextField nameTextField = new JTextField(25);

                JLabel passwordLab = new JLabel("用户密码:");
                final JTextField passwordTextField = new JTextField(25);

                JLabel ageLab = new JLabel("用户年龄:");
                final JTextField ageTextField = new JTextField(25);

                final JRadioButton marry = new JRadioButton();
                marry.setText("已婚");
                marry.setSelected(true);

                final JRadioButton noMarry = new JRadioButton();
                noMarry.setText("未婚");

                final ButtonGroup group = new ButtonGroup();
                group.add(marry);
                group.add(noMarry);

                JButton button = new JButton("确认添加");

                button.addActionListener(new ActionListener() {
                    @SuppressWarnings({ "unchecked", "rawtypes" })
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        Integer id = Integer.parseInt(idTextField.getText());
                        String username = nameTextField.getText();
                        String password = passwordTextField.getText();
                        int age = Integer.parseInt(ageTextField.getText());
                        boolean marry = false;
                        Enumeration<AbstractButton> en = group.getElements();
                        for (; en.hasMoreElements();) {
                            AbstractButton ab = en.nextElement();
                            if (ab.isSelected()) {
                                marry = ab.getText().equals("已婚") ? true
                                        : false;
                                break;
                            }
                        }
                        User user = new User(id, username, password, age, marry);
                        List<User> userList = new ArrayList<>();
                        userList.add(user);
                        userList.add(user);
                        userList.add(user);
                        tableModel.addRow(user);
                    }
                });

                dialog.setLayout(new FlowLayout());
                dialog.add(idLab);
                dialog.add(idTextField);
                dialog.add(nameLab);
                dialog.add(nameTextField);
                dialog.add(passwordLab);
                dialog.add(passwordTextField);
                dialog.add(ageLab);
                dialog.add(ageTextField);
                dialog.add(marry);
                dialog.add(noMarry);

                dialog.add(button);

                dialog.setVisible(true);
            }
        });

        deleteBtn.addActionListener(new ActionListener() {
            @SuppressWarnings("rawtypes")
            @Override
            public void actionPerformed(ActionEvent e) {
                int rowIndex = table.getSelectedRow();
                ((ElegantTableModel)table.getModel()).deleteRow(rowIndex);
            }
        });


        deleteBtn2.addActionListener(new ActionListener() {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            @Override
            public void actionPerformed(ActionEvent e) {
                int rowIndex = table.getSelectedRow();

                ElegantTableModel<User> tableModel = ((ElegantTableModel)table.getModel());
                User u = tableModel.getData(rowIndex);
                tableModel.deleteRow(u);
            }
        });

        updateBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                final int rowIndex = table.getSelectedRow();
                if(!table.isRowSelected(rowIndex)) {
                    JOptionPane.showMessageDialog(frame, "请选择数据条目");
                    return;
                }

                @SuppressWarnings("rawtypes")
                final ElegantTableModel tableModel = ((ElegantTableModel)table.getModel());
                /*
                 //传统的方式是需要通过
                    for(int i = 0;i < tableModel.getColumnCount();i++){
                        tableModel.getValueAt(rowIndex, i);
                    }
                */
                //现在我们采用基于OO的获取
                User user = (User) tableModel.getData(rowIndex);

                JDialog dialog = new JDialog(frame, true);
                dialog.setSize(300, 300);

                JLabel idLab = new JLabel("用户编号:");
                final JTextField idTextField = new JTextField(String.valueOf(user.getId()),25);


                JLabel nameLab = new JLabel("用户姓名");
                final JTextField nameTextField = new JTextField(user.getUsername(),25);

                JLabel passwordLab = new JLabel("用户密码:");
                final JTextField passwordTextField = new JTextField(user.getPassword(),25);

                JLabel ageLab = new JLabel("用户年龄:");
                final JTextField ageTextField = new JTextField(String.valueOf(user.getAge()),25);

                final JRadioButton marry = new JRadioButton();
                marry.setText("已婚");

                final JRadioButton noMarry = new JRadioButton();
                noMarry.setText("未婚");

                if(user.getIsMarry()){
                    marry.setSelected(true);
                }
                else{
                    noMarry.setSelected(true);
                }

                final ButtonGroup group = new ButtonGroup();
                group.add(marry);
                group.add(noMarry);

                JButton button = new JButton("确认更新");

                button.addActionListener(new ActionListener() {
                    @SuppressWarnings({ "unchecked"})
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.setVisible(false);
                        Integer id = Integer.parseInt(idTextField.getText());
                        String username = nameTextField.getText();
                        String password = passwordTextField.getText();
                        int age = Integer.parseInt(ageTextField.getText());
                        boolean marry = false;
                        Enumeration<AbstractButton> en = group.getElements();
                        for (; en.hasMoreElements();) {
                            AbstractButton ab = en.nextElement();
                            if (ab.isSelected()) {
                                marry = ab.getText().equals("已婚") ? true
                                        : false;
                                break;
                            }
                        }
                        User user = new User(id, username, password, age, marry);
                        tableModel.setData(rowIndex, user);
                    }
                });

                dialog.setLayout(new FlowLayout());
                dialog.add(idLab);
                dialog.add(idTextField);
                dialog.add(nameLab);
                dialog.add(nameTextField);
                dialog.add(passwordLab);
                dialog.add(passwordTextField);
                dialog.add(ageLab);
                dialog.add(ageTextField);
                dialog.add(marry);
                dialog.add(noMarry);

                dialog.add(button);

                dialog.setVisible(true);
            }
        });

        frame.add(panel, BorderLayout.SOUTH);

        frame.setVisible(true);
    }

}

